var baseSrc = document.scripts[document.scripts.length - 1].src;

(function($){
	$.PPPSearch = function(query,options){
		if(!(this instanceof $.PPPSearch)){
            return new $.PPPSearch(query, options);
        }
		
		if(typeof query === "object"){
			options = query;
			query = options.query;
		}
		
		var self = this;
		
		self.options = $.extend({}, $.PPPSearch.defaultOptions, options);
		
		self.options.ajaxUrl = baseSrc.substring(0,baseSrc.lastIndexOf("/")+1) + self.options.ajaxUrl;
		
		var init = function(){
			if(!self.options.allowNullQuery && isNullOrEmpty(query)){
				return ;
			}
			self.options.query=query;
			self.page(1);
		}
		
		this.page = function(num){
			if(!num || num < 1){
        		num = 1;
        	} else {
        		self.options.page.pageNum = num;
        	}
			
			self.options.config.start = (num-1)*self.options.page.pagerSize;
			self.options.config.hit = self.options.page.pagerSize;
			
			$.ajax({
        		url: self.options.ajaxUrl,
        		type:"post",
        		data: {query:JSON.stringify(self.options)},
        		async:false,
        		dataType:"json",
        		success: function(data){ 
        			if(data.status == "OK"){
        				self.options.onSuccess(data.result);
        			}else{
        				self.options.onError(data);
        			}
        		},
        		error: function(msg){
        			self.options.onError(msg);
        		}
        	});
			
		}
		
		this.refresh = function(){
			self.page(self.options.page.pageNum);
		}
		
		this.search = function(query){
			if(!self.options.allowNullQuery && isNullOrEmpty(query)){
				return ;
			}
			self.options.query=query;
			search.page(1);
		}
	}
	

	var isNullOrEmpty = function(strVal) {
		if (strVal == '' || strVal == null || strVal == undefined) {
			return true;
		} else {
			return false;
		}
	}
	
	$.PPPSearch.defaultOptions = {
		page:{
			pageNum:1,
			pagerSize:20
		},
		config:{
			start:0,
			hit:20
		},
		ajaxUrl:"ppp.jsp",
		allowNullQuery:false
	}
})(jQuery);
